#include "stdafx.h"
#include "ThreadLocalStorage.h"

using namespace std;
using namespace ISAPI_Python::Win32Helpers;

DWORD ThreadLocalStorage::Init() {
	DWORD tlsIndex = TlsAlloc();

	if(tlsIndex == TLS_OUT_OF_INDEXES) {
		throw exception();
	}

	return tlsIndex;
}

ThreadLocalStorage::ThreadLocalStorage() :
	TlsIndex( Init() ) {
}

ThreadLocalStorage::~ThreadLocalStorage() {
	TlsFree(TlsIndex);
}

TlsMap& ThreadLocalStorage::Data() const {
	LPTlsMap lpData = (LPTlsMap)TlsGetValue(TlsIndex);

	if(lpData == NULL) {
		lpData = new TlsMap();

		if(0 == TlsSetValue(TlsIndex, lpData)) {
			throw exception();
		}
	}

	return *lpData;
}

ThreadLocalStorage& ThreadLocalStorage::Current() {
	static ThreadLocalStorage TLSManager;
	return TLSManager;
}